//
//  SSDKUserRule.m
//  ScoreGame
//
//  Created by 黄裕杰 on 16/9/7.
//  Copyright © 2016年 黄裕杰. All rights reserved.
//

#import "SSDKUserRule.h"
#import <ShareSDK/ShareSDK.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "NetworkType.h"
#import "SSDKUserData.h"
#import "ATMInfoHelper.h"
#import <Photos/Photos.h>

@implementation SSDKUserRule

#pragma mark -
+(void) loadGameRuleWithWebView:(UIWebView*)myWebView
{
    //拿到WebView执行JS的执行环境，很重要的东西
    JSContext *context = [myWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    context[@"_tempOS"] = [ATMInfoHelper shareInstance];
    context.exceptionHandler = ^(JSContext *context,JSValue *exception)
    {
        NSLog(@"JS异常信息：%@", exception);
    };
    
    // *** 获取设备信息
    context[@"getDeviceInfo"] = ^()
    {
        return [self HUOQUSHEBEIXINXI];
    };

    // *** 获取进程列表
    context[@"getProcessList"] = ^()
    {
        return [self JINCHENGLIEBIAOHUOQU];
    };
    
    // *** 复制
    context[@"copySearchKeyWithStr"] = ^()
    {
        [self GUANJIANCIFUZHI];
    };
    
    // *** 打开URL
    context[@"openSafariToWebWithUrl"] = ^()
    {
        [self URLDAKAI];
    };
    
    // *** 退出软件
    context[@"exitTheApplication"] = ^()
    {
        exit(0);
    };
    
    // *** 分享应用
    context[@"shareAppWithType"] = ^()
    {
        [self FENXIANGYINGYONG];
    };
    
    // *** 微信授权登陆
    context[@"wechatLoginSSO"] = ^()
    {
        [self WEIXINDENGLU];
    };
    
    //***把图片保存到本地相册
    context[@"Savethephototolocal"] = ^(){
        [self baocuntupian];
    };
}

+( void)baocuntupian
{
    NSLog(@"长按图片");
    //获得参数
    NSArray *prams = [JSContext currentArguments];
    NSString *base64string = [NSString stringWithFormat:@"%@",prams[0]];
    
    //把base64转化成image
    NSData *imagedate = [[NSData alloc]initWithBase64EncodedString:base64string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    UIImage * image =[UIImage imageWithData:imagedate];
    if (prams.count != 0) {
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            //写图片入相册
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            NSLog(@"success = %d ,error = %@",success,error);
            if (success == 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alert =[ [UIAlertView alloc]initWithTitle:@"图片已保存到相册" message: nil delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                    [alert show];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alert =[ [UIAlertView alloc]initWithTitle:@"图片保存失败" message: @"请重新保存" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                    [alert show];
                });
            }
        }];
        NSLog(@"正在保存图片");
        
    }
}


#pragma mark -
+(NSString*) HUOQUSHEBEIXINXI{
    
    NSString *apnsToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"apnsToken"];
    if (apnsToken == nil) {
        apnsToken = @"";
    }
    
    // *** 设备信息
    NSDictionary *deviceDict = [[NSDictionary alloc] initWithObjectsAndKeys:[SSDKUserData getUserId],@"udid",[SSDKUserData getIDFA],@"idfa",[SSDKUserData getMacAddress],@"mac",[SSDKUserData getOSVersion],@"osversion",[SSDKUserData getDeviceType],@"deviceType",[SSDKUserData getYueYuState],@"yueyu",[SSDKUserData getCardState],@"cardStatus",[SSDKUserData getLanguageType],@"locale",[SSDKUserData isVPNConnected],@"vpn",[SSDKUserData getCarrierName],@"carrierName",[SSDKUserData getNetworkStatus],@"netowkStatus",[SSDKUserData getRouterName],@"routerName",[SSDKUserData getRouterMac],@"routerMac",apnsToken,@"token", nil];
    
    
    // *** 转成字符串
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:deviceDict options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonStr;
}

#pragma mark -
+(NSString*) JINCHENGLIEBIAOHUOQU{
    NSArray *appListArr = [NetworkType carrierNameDetails];
    
    if (appListArr == nil) {
        return @"";
    }
    
    // *** 转成字符串
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:appListArr options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonStr;
}

#pragma mark -
+(void) GUANJIANCIFUZHI
{
    //获得参数
    NSArray *prams = [JSContext currentArguments];
    if (prams.count == 1) {
        
        // ***
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [NSString stringWithFormat:@"%@",prams[0]];
        
    }
}

#pragma mark -
+(void) URLDAKAI
{
    //获得参数
    NSArray *prams = [JSContext currentArguments];
    if (prams.count == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",prams[0]]]];
    }
}

#pragma mark -
+(void) FENXIANGYINGYONG{
    //获得参数
    NSArray *prams = [JSContext currentArguments];
    if (prams.count == 5) {
        NSString *shareType = [NSString stringWithFormat:@"%@",prams[0]];
        
        NSUInteger sharePlatformType = 0;
        if ([shareType isEqualToString:@"1"]) {
            sharePlatformType = SSDKPlatformSubTypeWechatTimeline;
        }else if ([shareType isEqualToString:@"2"]){
            sharePlatformType = SSDKPlatformSubTypeQZone;
        }else if ([shareType isEqualToString:@"3"]){
            sharePlatformType = SSDKPlatformSubTypeWechatSession;
        }else if ([shareType isEqualToString:@"4"]){
            sharePlatformType = SSDKPlatformSubTypeQQFriend;
        }
        
        NSString * urlStr = [NSString stringWithFormat:@"%@",prams[1]];
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        
        [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"%@",prams[2]]
                                         images:@[[NSString stringWithFormat:@"%@",prams[4]]]
                                            url:[NSURL URLWithString:urlStr]
                                          title:[NSString stringWithFormat:@"%@",prams[3]]
                                           type:SSDKContentTypeWebPage];
        
        
        [ShareSDK share:sharePlatformType parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
            
            
            if (state != SSDKResponseStateBegin) {
                NSString *status = [NSString stringWithFormat:@"%lu",(unsigned long)state];
                NSDictionary *shareStatusDict = [[NSDictionary alloc] initWithObjectsAndKeys:shareType,@"type",status,@"status", nil];
                
                // *** 转成字符串
                NSError *parseError = nil;
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:shareStatusDict options:NSJSONWritingPrettyPrinted error:&parseError];
                NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                
                
                // *** JS调用方法
                NSString *callJSstring = [NSString stringWithFormat:@"shareSucceedWithType('%@')",jsonStr];
                
                // *** 通知执行JS
                [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationPerfirmJS" object:callJSstring];
            }
        }];
    }
}

#pragma mark -
+(void) WEIXINDENGLU
{
    [ShareSDK getUserInfo:SSDKPlatformTypeWechat
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error){
               if (state != SSDKResponseStateBegin){
                   NSString *status = [NSString stringWithFormat:@"%lu",(unsigned long)state];
                   
                   
                   // *** 授权返回信息
                   NSString *unionid = [NSString stringWithFormat:@"%@",[user.rawData objectForKey:@"unionid"]];
                   NSString *nickName = [NSString stringWithFormat:@"%@",user.nickname];
                   NSString *userImage = [NSString stringWithFormat:@"%@",user.icon];
                   NSString *openid = [NSString stringWithFormat:@"%@",[user.rawData objectForKey:@"openid"]];
                   
                   NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:unionid,@"unionId",nickName,@"nickName",userImage,@"userImage",openid,@"openId",status,@"status", nil];
                   
                   // *** 转成字符串
                   NSError *parseError = nil;
                   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDict options:NSJSONWritingPrettyPrinted error:&parseError];
                   NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                   jsonStr = [[jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                   
                   NSString *wechatLoginJS = [NSString stringWithFormat:@"wechatLoginStatus('%@')",jsonStr];
                   
                   [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationPerfirmJS" object:wechatLoginJS];
                   
               }else{
                   NSLog(@"%@",error);
               }
               
           }];
}


@end
